package com.landinfo.web.rest;

import com.alibaba.fastjson.JSON;
import com.codahale.metrics.annotation.Timed;
import com.landinfo.domain.EquipmentManagement;
import com.landinfo.service.EquipmentManagementService;
import com.landinfo.web.rest.util.HeaderUtil;
import com.landinfo.web.rest.util.PaginationUtil;
import com.landinfo.service.dto.EquipmentManagementDTO;
import io.swagger.annotations.ApiParam;
import io.github.jhipster.web.util.ResponseUtil;
import org.apache.commons.collections.IteratorUtils;
import org.hibernate.exception.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;

import java.util.Iterator;
import java.util.List;
import java.util.Optional;

/**
 * REST controller for managing EquipmentManagement.
 */
@RestController
@RequestMapping("/api")
public class EquipmentManagementResource {

    private final Logger log = LoggerFactory.getLogger(EquipmentManagementResource.class);

    private static final String ENTITY_NAME = "equipmentManagement";

    private final EquipmentManagementService equipmentManagementService;

    public EquipmentManagementResource(EquipmentManagementService equipmentManagementService) {
        this.equipmentManagementService = equipmentManagementService;
    }

    /**
     * POST  /equipment-managements : Create a new equipmentManagement.
     *
     * @param equipmentManagementDTO the equipmentManagementDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new equipmentManagementDTO, or with status 400 (Bad Request) if the equipmentManagement has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/equipment-managements")
    @Timed
    public ResponseEntity<EquipmentManagementDTO> createEquipmentManagement(@Valid @RequestBody EquipmentManagementDTO equipmentManagementDTO) throws URISyntaxException {
        log.debug("REST request to save EquipmentManagement : {}", equipmentManagementDTO);
        try {
            if (equipmentManagementDTO.getId() != null) {
                return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new equipmentManagement cannot already have an ID")).body(null);
            }
            EquipmentManagementDTO result = equipmentManagementService.save(equipmentManagementDTO);
            return ResponseEntity.created(new URI("/api/equipment-managements/" + result.getId()))
                    .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
                    .body(result);
        } catch (Exception ex) {
            if (ex instanceof ConstraintViolationException || ex instanceof DataIntegrityViolationException) {
                return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "The value is not unique")).body(null);
            } else {
                return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", ex.getMessage())).body(null);
            }
        }
    }

    /**
     * PUT  /equipment-managements : Updates an existing equipmentManagement.
     *
     * @param equipmentManagementDTO the equipmentManagementDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated equipmentManagementDTO,
     * or with status 400 (Bad Request) if the equipmentManagementDTO is not valid,
     * or with status 500 (Internal Server Error) if the equipmentManagementDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/equipment-managements")
    @Timed
    public ResponseEntity<EquipmentManagementDTO> updateEquipmentManagement(@Valid @RequestBody EquipmentManagementDTO equipmentManagementDTO) throws URISyntaxException {
        log.debug("REST request to update EquipmentManagement : {}", equipmentManagementDTO);
        if (equipmentManagementDTO.getId() == null) {
            return createEquipmentManagement(equipmentManagementDTO);
        }
        EquipmentManagementDTO result = equipmentManagementService.save(equipmentManagementDTO);
        return ResponseEntity.ok()
                .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, equipmentManagementDTO.getId().toString()))
                .body(result);
    }

    /**
     * GET  /equipment-managements : get all the equipmentManagements.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of equipmentManagements in body
     */
    @GetMapping("/equipment-managements")
    @Timed
    public ResponseEntity<List<EquipmentManagement>> getAllEquipmentManagements(@ApiParam Pageable pageable) {
        log.debug("REST request to get a page of EquipmentManagements");
//        Page<EquipmentManagementDTO> page = equipmentManagementService.findAll(pageable);
//        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/equipment-managements");
//        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
//        for(int i=0;i<20;i++){
//            EquipmentManagementDTO equipmentManagementDTO=new EquipmentManagementDTO();
//            equipmentManagementDTO.setImei(i+"");
//            equipmentManagementDTO.setName(i+"");
//            try {
//                this.createEquipmentManagement(equipmentManagementDTO);
//            } catch (URISyntaxException e) {
//                e.printStackTrace();
//            }
//        }
        Iterator<EquipmentManagement> page = equipmentManagementService.findAll().iterator();
        return new ResponseEntity<>(IteratorUtils.toList(page), HttpStatus.OK);
    }

    /**
     * GET  /equipment-managements/:id : get the "id" equipmentManagement.
     *
     * @param id the id of the equipmentManagementDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the equipmentManagementDTO, or with status 404 (Not Found)
     */
    @GetMapping("/equipment-managements/{id}")
    @Timed
    public ResponseEntity<EquipmentManagementDTO> getEquipmentManagement(@PathVariable Long id) {
        log.debug("REST request to get EquipmentManagement : {}", id);
        EquipmentManagementDTO equipmentManagementDTO = equipmentManagementService.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(equipmentManagementDTO));
    }

    /**
     * GET  /equipment-managements/:id : get the "id" equipmentManagement.
     *
     * @param imei the id of the equipmentManagementDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the equipmentManagementDTO, or with status 404 (Not Found)
     */
    @GetMapping("/equipment-managements/find/{imei}")
    @Timed
    public ResponseEntity<String> findEquipmentManagementByImei(@PathVariable String imei) {
        log.debug("REST request to get EquipmentManagement : {}", imei);
        EquipmentManagement equipmentManagement = equipmentManagementService.findByImei(imei);
        return ResponseEntity.ok(JSON.toJSONString(equipmentManagement));
    }

    /**
     * DELETE  /equipment-managements/:id : delete the "id" equipmentManagement.
     *
     * @param id the id of the equipmentManagementDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/equipment-managements/{id}")
    @Timed
    public ResponseEntity<Void> deleteEquipmentManagement(@PathVariable Long id) {
        log.debug("REST request to delete EquipmentManagement : {}", id);
        equipmentManagementService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }
}
